package com.xbstar.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xbstar.bean.MsgInfo;

/**
 * Socket处理器
 * 
 * @author jiwf
 * @Date 2016年9月3日
 */
@Component
public class MyWebSocketHandler implements WebSocketHandler {
	public static final Map<Long, WebSocketSession> userSocketSessionMap;
	@Resource
	MsgControll mc;
	static {
		userSocketSessionMap = new HashMap<Long, WebSocketSession>();
	}

	/**
	 * 建立连接后
	 */
	public void afterConnectionEstablished(WebSocketSession session)
			throws Exception {
//		Long uid = (Long) session.getAttributes().get("uid");
//		if (userSocketSessionMap.get(uid) == null) {
//			userSocketSessionMap.put(uid, session);
//		}
	}

	/**
	 * 消息处理，在客户端通过Websocket API发送的消息会经过这里，然后进行相应的处理
	 */
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		System.out.println();	
		if(message.getPayloadLength()==0)return;
		String tstring=message.getPayload().toString();
		try {
			JSONObject json=new JSONObject(tstring);
			if(MsgAttr.AUTHOR_TYPE.equals(json.get(MsgAttr.MSG_TYPE).toString())){
				//认证接口，缓存用户会话
				Long uuid=json.getLong("uuid");
				if (userSocketSessionMap.get(uuid) == null) {
					userSocketSessionMap.put(uuid, session);
				}
			}else if(MsgAttr.CHAT_TYPE.equals(json.get(MsgAttr.MSG_TYPE).toString())){
				//MsgControll mc=new MsgControll();
				json.put("id", 0);
				MsgInfo msg=new Gson().fromJson(json.toString(),MsgInfo.class);
				HashMap<Long, MsgInfo> hands=mc.dissolveMsg(msg);
				Iterator<Entry<Long, MsgInfo>> it = hands
						.entrySet().iterator();
				while (it.hasNext()) {
					Entry<Long, MsgInfo>entry=it.next();
					sendMessageToUser(entry.getKey(), new TextMessage(new GsonBuilder().create().toJson(entry.getValue())));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		
//		session.sendMessage(new TextMessage("asddff"));
		//TODO 需要重新设计是否启动
		//			if(message.getPayloadLength()==0)return;
//			MsgInfo msg=new Gson().fromJson(message.getPayload().toString(),MsgInfo.class);
//			msg.setSendTime(new Date());
//			sendMessageToUser(msg.(), new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
	}

	/**
	 * 消息传输错误处理
	 */
	public void handleTransportError(WebSocketSession session,
			Throwable exception) throws Exception {
		if (session.isOpen()) {
			session.close();
		}
		Iterator<Entry<Long, WebSocketSession>> it = userSocketSessionMap
				.entrySet().iterator();
		// 移除Socket会话
		while (it.hasNext()) {
			Entry<Long, WebSocketSession> entry = it.next();
			if (entry.getValue().getId().equals(session.getId())) {
				userSocketSessionMap.remove(entry.getKey());
				System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
				break;
			}
		}
	}

	/**
	 * 关闭连接后
	 */
	public void afterConnectionClosed(WebSocketSession session,
			CloseStatus closeStatus) throws Exception {
		System.out.println("Websocket:" + session.getId() + "已经关闭");
		Iterator<Entry<Long, WebSocketSession>> it = userSocketSessionMap
				.entrySet().iterator();
		// 移除Socket会话
		while (it.hasNext()) {
			Entry<Long, WebSocketSession> entry = it.next();
			if (entry.getValue().getId().equals(session.getId())) {
				userSocketSessionMap.remove(entry.getKey());
				System.out.println("Socket会话已经移除:用户ID" + entry.getKey());
				break;
			}
		}
	}

	public boolean supportsPartialMessages() {
		return false;
	}

	/**
	 * 给所有在线用户发送消息
	 * 
	 * @param message
	 * @throws IOException
	 */
	public void broadcast(final TextMessage message) throws IOException {
		Iterator<Entry<Long, WebSocketSession>> it = userSocketSessionMap
				.entrySet().iterator();

		// 多线程群发
		while (it.hasNext()) {

			final Entry<Long, WebSocketSession> entry = it.next();

			if (entry.getValue().isOpen()) {
				// entry.getValue().sendMessage(message);
				new Thread(new Runnable() {

					public void run() {
						try {
							if (entry.getValue().isOpen()) {
								entry.getValue().sendMessage(message);
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

				}).start();
			}

		}
	}

	/**
	 * 给某个用户发送消息
	 * 
	 * @param userName
	 * @param message
	 * @throws IOException
	 */
	public void sendMessageToUser(Long uid, TextMessage message)
			throws IOException {
		//uid=12345678L;
		WebSocketSession session = userSocketSessionMap.get(uid);
		if (session != null && session.isOpen()) {
			session.sendMessage(message);
		}
	}

}
